package com.tianji.aigc.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.tianji.aigc.agent.Agent;
import com.tianji.aigc.config.SystemPromptConfig;
import com.tianji.aigc.enums.AgentTypeEnum;
import com.tianji.aigc.enums.ChatEventTypeEnum;
import com.tianji.aigc.service.ChatService;
import com.tianji.aigc.vo.ChatEventVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Map;

/**
 * @author zgp
 * @version V1.0
 * @date 2025-04-24 17:08
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AgentChatServiceImpl implements ChatService {
    private final ChatClient openAiChatClient;
    private final SystemPromptConfig systemPromptConfig;
    /**
     * 流式对话聊天
     *
     * @param question  用户问题
     * @param sessionId 会话id
     * @return 大模型返回内容
     */
    @Override
    public Flux<ChatEventVO> chat(String question, String sessionId) {
        // 1. 调用意图分析智能体，分析用户意图
        Agent routeAgent = findAgentByType(AgentTypeEnum.ROUTE);
        String routeAgentResult = routeAgent.process(question, sessionId);
        // 2. 根据意图分析结果，调用对应的智能体，进行对话
        AgentTypeEnum agentTypeEnum = AgentTypeEnum.agentNameOf(routeAgentResult);
        if(ObjUtil.isNull(agentTypeEnum)){
            // 用户无其它意图，直接返回数据
            ChatEventVO chatEventVO = ChatEventVO.builder().eventType(ChatEventTypeEnum.DATA.getValue()).eventData(routeAgentResult).build();
            return Flux.just(chatEventVO, ChatEventVO.builder().eventType(ChatEventTypeEnum.STOP.getValue()).build());
        }
        // 3. 根据智能体类型，获取对应智能体Bean
        Agent agent = findAgentByType(agentTypeEnum);
        // 4. 调用其它智能体，进行对话
        return agent.processStream(question, sessionId);
    }

    /**
     * 停止内容生成（中断流的响应，大模型内部依旧在生成内容）
     *
     * @param sessionId 会话id
     */
    @Override
    public void stopChat(String sessionId) {
        this.findAgentByType(AgentTypeEnum.ROUTE).stop(sessionId);
    }

    /**
     * 根据智能体类型，获取对应智能体Bean
     * @param agentTypeEnum 智能体类型
     * @return 智能体实现
     */
    private Agent findAgentByType(AgentTypeEnum agentTypeEnum){
        // 1. 校验
        if(ObjUtil.isNull(agentTypeEnum)){
            return null;
        }
        // 2. 根据智能体类型，获取对应智能体Bean
        Map<String, Agent> agentMap = SpringUtil.getBeansOfType(Agent.class);
        if(MapUtil.isEmpty(agentMap)){
            return null;
        }
        for (Agent agent : agentMap.values()) {
            if (agentTypeEnum == agent.getAgentType()) {
                // 找到返回智能体
                return agent;
            }
        }
        // 3. 未找到对应智能体
        return null;

    }

    /**
     * 文本对话
     *
     * @param question 用户问题
     * @return
     */
    @Override
    public String chatText(String question) {
        return openAiChatClient.prompt()
                .system(systemPromptConfig.getTextSystemMessage().get())
                .user(question)
                .call()
                .content();
    }
}
